package com.api.server.controller;


/*登录*/

import com.api.server.pojo.*;
import com.api.server.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

@Api(tags = "AdminController")
@RestController

public class AdminController {

    /**
     * 登录
     */
    @Autowired
    public IUserService userService;



    @ApiOperation(value = "登陆之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return userService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/user/info")
    public User getAdminInfo(Principal principal){
        if (null==principal){
            return null;
        }
        String username = principal.getName();
        User user = userService.getAdminByUserName(username);
        user.setUserpassword(null);
        return user;
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功！");
    }


    @ApiOperation(value = "删除账户")
    @DeleteMapping("/deleteaccount/{id}")
    public RespBean deleteaccount(@PathVariable("id") Long id){
        User user = userService.getById(id);
        if (userService.getById(id)==null){
            return Result.fail("该账户不存在！");
        }
        userService.deleteaccount(user.getId());
        return RespBean.success("删除账户成功！");
    }


    @ApiOperation(value = "根据id查询账户信息")
    @GetMapping("/user/{id}")
    public RespBean user(@PathVariable("id") Long id){
        User user = userService.getById(id);
        if (userService.getById(id)==null){
            return Result.fail("该账户不存在！");
        }
        userService.userById(user.getId());
        user.setUserpassword(null);
        return Result.success(200,"查询成功！",user);
    }


    //根据权限等级获取用户列表
    @ApiOperation(value = "根据权限等级获取用户列表")
    @GetMapping("/users")
    public RespBean users(UserListPage userListPage){
        Map<String,Object> map = userService.page(userListPage);

        return Result.success("获取普通用户列表成功！",map);
    }

    //根据id修改账号
    @ApiOperation(value = "根据id修改账号")
    @PutMapping("/updata")
    public RespBean updata(@RequestBody User user){
        if (userService.getById(user.getId())==null){
            return Result.fail("该账户不存在！");
        }
        int row = userService.updatebyId(user);
        user.setUserpassword(null);
        return Result.success(200,"更新成功！",row);
    }
}
